package com.customer.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.customer.mall.domain.vo.BannerVO;
import com.customer.mall.mapper.BannerMapper;
import com.customer.mall.domain.Banner;
import com.customer.mall.service.IBannerService;
import com.customer.mall.util.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author BaiGGG
 * @since 2023-06-25
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements IBannerService {

    @Override
    public ResponseResult<Page<BannerVO>> pageBanner(Integer pageNum, Integer pageSize) {
        Page<Banner> bannerPage = new Page<>(pageNum, pageSize);
        Page<BannerVO> bannerVOPage = new Page<>();
        bannerVOPage.setRecords(page(bannerPage).getRecords().stream().map(item ->
                new BannerVO(item.getId(), item.getImg(), item.getUrl(), item.getDescription(), item.getState())
                ).collect(Collectors.toList()));
        BeanUtils.copyProperties(bannerPage, bannerVOPage, "records");
        return ResponseResult.okResult(bannerVOPage);
    }

    @Override
    public ResponseResult<BannerVO> getBannerById(Integer id) {
        Banner getBanner = getById(id);
        if(Objects.isNull(getBanner)){
            return ResponseResult.failResult();
        }
        BannerVO resBanner = new BannerVO();
        BeanUtils.copyProperties(getBanner, resBanner);
        return ResponseResult.okResult(resBanner);
    }

    @Override
    public ResponseResult<String> insertBanner(Banner banner) {
        if(!save(banner)){
            return ResponseResult.failResult();
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<String> updateBanner(Banner banner) {
        if(!updateById(banner)){
            return ResponseResult.failResult("修改失败");
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<String> setState(Integer id) {
        Banner getBanner = getById(id);
        getBanner.setState(getBanner.getState() == 0 ? 1 : 0);
        if(!updateById(getBanner)){
            return ResponseResult.failResult("修改失败");
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<Banner> getBannerAllById(Integer id) {
        Banner getBanner = getById(id);
        if(Objects.isNull(getBanner)){
            return ResponseResult.failResult("查询失败");
        }
        return ResponseResult.okResult(getBanner);
    }


}
